package com.mogujie.tt.imservice.manager;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import com.mogujie.tt.config.ForgotPasswordConstant;
import com.mogujie.tt.config.RegisterConstant;
import com.mogujie.tt.customview.control.PhoneVerificationCode;
import com.mogujie.tt.imservice.event.ForgotPasswordEvent;
import com.mogujie.tt.utils.HttpUtilsApache;
import com.mogujie.tt.utils.JsonUtil;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;

import de.greenrobot.event.EventBus;

/**
 * Created by user on 2015/9/18.
 */
public class IMForgotPasswordManager extends IMManager {


    /**单例模式*/
    private static IMForgotPasswordManager inst = new IMForgotPasswordManager();
    public static IMForgotPasswordManager instance() {
        return inst;
    }

    @Override
    public void doOnStart() {
    }

    @Override
    public void reset() {
    }

    /**
     * 实现自身的事件驱动
     * @param event
     */
    public void triggerEvent(ForgotPasswordEvent.UserName event) {

        EventBus.getDefault().postSticky(event);
    }
    public void triggerEvent(ForgotPasswordEvent.UserNewPassWord event) {

        EventBus.getDefault().postSticky(event);
    }

    public void triggerEvent(ForgotPasswordEvent.AnswerQuestion event) {

        EventBus.getDefault().postSticky(event);
    }

    /**
     * 检查用户是否存在
     * @param UserName
     * @param context
     */
    public void checkWhetherUserExist(String UserName,Context context,PhoneVerificationCode mPhoneVerificationCode){

        new UserExistTask(UserName,context,mPhoneVerificationCode).executeOnExecutor(Executors.newCachedThreadPool());
    }


    /**
     * 判断注册密码是否一致
     */
    public void passwordsConsistent(String pwd1,String pwd2){

        if(pwd1.equals(pwd2)){
            triggerEvent(ForgotPasswordEvent.UserNewPassWord.USER_NEW_PASSWORD_SAME);
        }else{
            triggerEvent(ForgotPasswordEvent.UserNewPassWord.USER_NEW_PASSWORD_NO_SAME);
        }
    }
    public void SubmitUserNewPassword(Context context){

        new UserNewPasswordtTask(context).executeOnExecutor(Executors.newCachedThreadPool());
    }


    /**
     * 检查用户是否存在
     */
    private class UserExistTask extends AsyncTask<Void,Void,String> {
        Context context;
        String userName;
        PhoneVerificationCode mPhoneVerificationCode;
        JSONObject request;
        JSONObject rtjson;//json对象
        String newMessageInfo = "";

        public UserExistTask(String userName,Context context,PhoneVerificationCode mPhoneVerificationCode) {
            this.userName = userName;
            this.context =context;
            this.mPhoneVerificationCode = mPhoneVerificationCode;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected String doInBackground(Void... params) {
            Map<String, Object> parms = new HashMap<String ,Object>();
            parms.put("name", userName);
            request = new JSONObject();//新建json格式
            request = JsonUtil.jsonRequest(ForgotPasswordConstant.SERVER_NAME, ForgotPasswordConstant.REQUEST_USER_EXISTS, parms);
            String jsonstr = HttpUtilsApache.usHttpPostJson(ForgotPasswordConstant.SERVER_PATH, request);
            JsonUtil jsonUtil=new JsonUtil();//建立json验证
            if(jsonstr.length()>3){
                rtjson=jsonUtil.getOutputJson(jsonstr);
                Log.v("", "rtjson = " + rtjson);

            }else{
                newMessageInfo=HttpUtilsApache.errorMsg(jsonstr);//打印出错信息
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);

            if("".equals(newMessageInfo) || newMessageInfo==null)
            {
                if(rtjson!=null && !"".equals(rtjson)){

                    try {
                        String responseCode=rtjson.getString("response_code").toString();
                        if("-1".equals(responseCode)) {//存在

                            mPhoneVerificationCode.methods();
                             new MessageAuthenticationTask(context,userName).executeOnExecutor(Executors.newCachedThreadPool());

                        }else if("1".equals(responseCode)) {

                            Toast.makeText(context,"该用户没有注册",Toast.LENGTH_LONG).show();
                        }

                    } catch (Exception e) {}
                }
            }
            else {

                Toast.makeText(context, newMessageInfo, Toast.LENGTH_SHORT).show();
            }

        }
    }

    /**
     * 求请修改密码的手机验证码
     */
    private class   MessageAuthenticationTask  extends AsyncTask<Void,Void,String>{

        Context context;
        String userName;
        JSONObject request;
        JSONObject rtjson;//json对象
        String newMessageInfo = "";

        public MessageAuthenticationTask(Context context,String userName) {
            this.context = context;
            this.userName = userName;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected String doInBackground(Void... params) {
            Map<String, Object> parms = new HashMap<String ,Object>();
            parms.put("to_rece",userName);//提交手机号
            parms.put("msg_type","");
            request = new JSONObject();//新建json格式
            request = JsonUtil.jsonRequest(ForgotPasswordConstant.SMS_SERVER_NAME,ForgotPasswordConstant.REQUEST_USER_PHONE_CODE,parms);
            String jsonstr = HttpUtilsApache.usHttpPostJson(ForgotPasswordConstant.SERVER_PATH, request);
            JsonUtil jsonUtil=new JsonUtil();//建立json验证
            if(jsonstr.length()>3){
                rtjson=jsonUtil.getOutputJson(jsonstr);
                Log.v("","rtjson = "+rtjson);

            }else{
                newMessageInfo=HttpUtilsApache.errorMsg(jsonstr);//打印出错信息
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);

            if("".equals(newMessageInfo) || newMessageInfo==null)
            {
                if(rtjson!=null && !"".equals(rtjson)){

                    try {
                        String responseCode=rtjson.getString("response_code").toString();
                        if("1".equals(responseCode)) {
                         //   Toast.makeText(context,rtjson.getString("response_desc").toString(),Toast.LENGTH_LONG).show();
                            Toast.makeText(context,"短信已发送，请注意查收",Toast.LENGTH_LONG).show();
                        }else if("-1".equals(responseCode)) {
                        //    Toast.makeText(context,rtjson.getString("response_desc").toString(),Toast.LENGTH_LONG).show();
                            Toast.makeText(context,"获取短信失败",Toast.LENGTH_LONG).show();
                        }

                    } catch (Exception e) {}
                }
            }
            else {
                Toast.makeText(context, newMessageInfo, Toast.LENGTH_SHORT).show();
            }
        }
    }


    /**
     * 提交新密码
     */
    private class UserNewPasswordtTask extends AsyncTask<Void,Void,String> {
        Context context;
        JSONObject request;
        JSONObject rtjson;//json对象
        String newMessageInfo = "";

        public UserNewPasswordtTask(Context context) {
            this.context =context;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected String doInBackground(Void... params) {
            Map<String, Object> parms = new HashMap<String ,Object>();
            parms.put("uPwdNow",ForgotPasswordConstant.user_new_password);
            parms.put("name",ForgotPasswordConstant.user_name);
            parms.put("code",ForgotPasswordConstant.user_code);
            request = new JSONObject();//新建json格式
            request = JsonUtil.jsonRequest(ForgotPasswordConstant.SERVER_NAME, ForgotPasswordConstant.SUBMIT_NEW_PASSWORD, parms);
            String jsonstr = HttpUtilsApache.usHttpPostJson(ForgotPasswordConstant.SERVER_PATH, request);
            JsonUtil jsonUtil=new JsonUtil();//建立json验证
            if(jsonstr.length()>3){
                rtjson=jsonUtil.getOutputJson(jsonstr);
                Log.v("", "rtjson = " + rtjson);

            }else{
                newMessageInfo=HttpUtilsApache.errorMsg(jsonstr);//打印出错信息
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);

            if("".equals(newMessageInfo) || newMessageInfo==null)
            {
                if(rtjson!=null && !"".equals(rtjson)){

                    try {
                        String responseCode=rtjson.getString("response_code").toString();
                        if("-1".equals(responseCode)) {
                            triggerEvent(ForgotPasswordEvent.AnswerQuestion.ANSWER_QUESTION_NO_SAME);
                            Toast.makeText(context, "修改密码失败", Toast.LENGTH_LONG).show();
                        }else if("1".equals(responseCode)) {//修改密码成功
                            triggerEvent(ForgotPasswordEvent.AnswerQuestion.ANSWER_QUESTION_SAME);
                           // Toast.makeText(context, rtjson.getString("response_desc").toString(),Toast.LENGTH_LONG).show();
                            Toast.makeText(context, "密码修改成功",Toast.LENGTH_LONG).show();
                        }

                    } catch (Exception e) {}
                }
            }
            else {
                triggerEvent(ForgotPasswordEvent.AnswerQuestion.ANSWER_QUESTION_NO_SAME);
                Toast.makeText(context, newMessageInfo, Toast.LENGTH_SHORT).show();
            }
        }
    }

}
